<template>
  <div class="main">
    <div class="main-warpper">
      <div class="bread-crumb">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/home' }">我的好茶仓</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/user' }">个人中心</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/user/afterSales' }">售后管理</el-breadcrumb-item>
          <el-breadcrumb-item>申请售后</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="main-content-first">
        <!-- 一个商品的时候 -->
        <div class="prodcut-content" v-if="this.imgList.length === 0">
          <div class="product-img"><img :src="aftersaleList.productCover" width="100%" height="100%"/></div>
          <div class="product-name">
            <p class="name">{{aftersaleList.name}}</p>
            <p>规格：{{aftersaleList.attributeName}}</p>
          </div>
          <!-- <div class="add"><el-button type="primary" @click="add">+添加</el-button> </div> -->
        </div>
        <!-- 多个商品的时候 -->
        <!-- <div class="product-more"  v-if="this.imgList.length > 1">
          <div class="product-img" v-for="(item, index) in imgList" :key="index">
            <img :src="item" width="100%" height="100%">
          </div>
          <div class="add"><el-button type="primary" @click="add">+添加</el-button> </div>
        </div> -->
        <!-- 弹出商品层 -->
        <div class="product-pop" v-if="this.productPop">
          <div class="pop-dialog">
            <p class="title">可添加商品一起退换货</p>
            <div class="product-list">
              <div class="pro-detail" v-for="(item, index) in saleafteProducts" :key="index">
                <div class="check-box">
                  <el-checkbox v-model="item.checked" @change="checkOneBox(item)"></el-checkbox>
                </div>
                <div class="check-img"><img :src="item.productCover" width="100%" height="100%"></div>
                <div class="check-pro">
                  <p>{{item.name}}</p>
                  <p>规格：{{item.attributeName}} <span>*{{item.amount}}</span> </p>
                </div>
              </div>
            </div>
            <div class="footer">
              <div><el-checkbox v-model="selectAll" label="全选" @change="checkAll"></el-checkbox></div>
              <div class="footer-btn">
                <el-button type="primary" @click="submit">提交</el-button>
                <el-button @click="cancel">取消</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="after-sale-detail">
        <div class="main-content-second">
          <el-form ref="saleFrom" :model="saleFrom" :rules="saleAfterRules" label-width="80px" size="mini" label-position="left">
            <el-form-item label="售后类型" prop="saleafterType">
              <el-radio-group v-model="saleFrom.saleafterType">
                <el-radio :label="0">仅退款</el-radio>
                <el-radio :label="2" :disabled='disabedChec'>仅换货</el-radio>
                <el-radio :label="1" :disabled='disabedChec'>退款退货</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="货物状态" prop="goodStatus">
              <el-radio-group v-model="saleFrom.goodStatus">
                <el-radio :label="0">已收到货</el-radio>
                <el-radio :label="1">未收到货</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="售后原因" prop="saleafterCause">
              <el-select clearable class="db" placeholder="请选择售后原因" v-model="saleFrom.saleafterCause" width="250px">
                <el-option v-for="(key, value, index) in afterSaleCause.Types" :key="index" :value="value" :label="key"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="退款金额" prop="money">
              <span class="money">￥{{price}}</span>
               <!-- <span class="into">（最多可退84.00，含邮费10.00）</span> -->
            </el-form-item>
            <el-form-item label="退款说明" prop="refundExplain">
              <textarea class="textarea" v-model="saleFrom.refundExplain" cols="30" rows="10" placeholder="不少于十个字"></textarea>
            </el-form-item>
            <el-form-item label="退款凭证">
              <div class="uploader-bar">
                  <!-- 门头 -->
                  <div class="single-uploader">
                    <el-upload
                      :action="$api + '/pcUtils/uploadFile'"
                      :show-file-list="false"
                      :on-success="uploadSuccesspictureMessage01"
                      :before-upload="beforeUpload"
                      accept="image/gif,image/jpeg,image/jpg,image/png">
                      <el-popover class="uploader-img" v-if="saleFrom.pictureMessage01" placement="right" width="40%" trigger="hover">
                        <a class="perview-img" target="_blank" :href="saleFrom.pictureMessage01"><img :src="saleFrom.pictureMessage01"></a>
                        <img :src="saleFrom.pictureMessage01" slot="reference">
                      </el-popover>
                      <i v-if="saleFrom.pictureMessage01" class="el-icon-circle-close btn-delete" @click.stop="delImg('saleFrom', 'pictureMessage01')"></i>
                      <i v-else class="el-icon-plus"></i>
                    </el-upload>
                    <p class="uploader-tip">1</p>
                  </div>
                  <!-- 正面 -->
                  <div class="single-uploader">
                    <el-upload
                      :action="$api + '/pcUtils/uploadFile'"
                      :show-file-list="false"
                      :on-success="uploadSuccesspictureMessage02"
                      :before-upload="beforeUpload"
                      accept="image/gif,image/jpeg,image/jpg,image/png">
                      <el-popover class="uploader-img" v-if="saleFrom.pictureMessage02" placement="right" width="40%" trigger="hover">
                        <a class="perview-img" target="_blank" :href="saleFrom.pictureMessage02"><img :src="saleFrom.pictureMessage02"></a>
                        <img :src="saleFrom.pictureMessage02" slot="reference">
                      </el-popover>
                      <i v-if="saleFrom.pictureMessage02" class="el-icon-circle-close btn-delete" @click.stop="delImg('saleFrom', 'pictureMessage02')"></i>
                      <i v-else class="el-icon-plus"></i>
                    </el-upload>
                    <p class="uploader-tip">2</p>
                  </div>
                  <!-- 左边 -->
                  <div class="single-uploader">
                    <el-upload
                      :action="$api + '/pcUtils/uploadFile'"
                      :show-file-list="false"
                      :on-success="uploadSuccesspictureMessage03"
                      :before-upload="beforeUpload"
                      accept="image/gif,image/jpeg,image/jpg,image/png">
                      <el-popover class="uploader-img" v-if="saleFrom.pictureMessage03" placement="right" width="40%" trigger="hover">
                        <a class="perview-img" target="_blank" :href="saleFrom.pictureMessage03"><img :src="saleFrom.pictureMessage03"></a>
                        <img :src="saleFrom.pictureMessage03" slot="reference">
                      </el-popover>
                      <i v-if="saleFrom.pictureMessage03" class="el-icon-circle-close btn-delete" @click.stop="delImg('saleFrom', 'pictureMessage03')"></i>
                      <i v-else class="el-icon-plus"></i>
                    </el-upload>
                    <p class="uploader-tip">3</p>
                  </div>
                </div>
            </el-form-item>
          </el-form>
        </div>
        <div class="info-sub">
          <el-button type="primary" @click="subFrom('saleFrom')" v-loading="isLoading">提交</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {afterSaleCause, goodsStatus, saleafterType, afterSaleTypes} from '@/util/enums'
import {saleAfterRules} from '@/data/rules'
export default {
  data () {
    return {
      disabedChec: false, // 是否能够点击 仅退款 仅退货状态
      productPop: false, // 弹出层
      aftersaleList: {}, // 售后详情列表
      afterSaleCause: afterSaleCause, // 售后原因
      goodsStatus: goodsStatus, // 是否收到货
      saleafterType: saleafterType, // 售后类型
      afterSaleTypes: afterSaleTypes, // 售后状态
      saleafteProducts: [], // 售后所有商品
      saleAfterRules: saleAfterRules,
      orderId: '', // 订单id
      checkOne: [],
      checkAllId: [], // 全选id
      imgList: [], // 多个商品售后的图片
      selectAll: false, // 是否为全选
      saleFrom: {
        saleafterType: '',
        goodStatus: '',
        saleafterCause: '',
        refundExplain: '',
        pictureMessage01: '',
        pictureMessage02: '',
        pictureMessage03: '',
        pictureList: []
      },
      priceIds: [], // 售后金额id
      price: '',
      isLoading: false
    }
  },
  mounted () {
    this.getData()
  },
  methods: {
    getData () {
      this.$http.post(this.$api + '/pc/orderSaleafter/getSaleafterDetail', {
        saleafterId: this.$route.query.saleafterId
      }).then(res => {
        if (res.responseCode === '0000') {
          this.aftersaleList = res.data
          this.orderId = res.data.orderId
          if (this.aftersaleList.orderStatus === 2) {
            this.disabedChec = true
          }
          this.getProduct()
          // 售后详情
          this.saleFrom.saleafterType = this.aftersaleList.saleafterType
          this.saleFrom.goodStatus = this.aftersaleList.goodsStatus
          this.saleFrom.saleafterCause = this.aftersaleList.saleafterCause + ''
          this.saleFrom.refundExplain = this.aftersaleList.refundExplain
          if (this.aftersaleList.refundProve.split(',')[0]) {
            this.saleFrom.pictureMessage01 = this.aftersaleList.refundProve.split(',')[0]
          }
          if (this.aftersaleList.refundProve.split(',')[1]) {
            this.saleFrom.pictureMessage02 = this.aftersaleList.refundProve.split(',')[1]
          }
          if (this.aftersaleList.refundProve.split(',')[2]) {
            this.saleFrom.pictureMessage03 = this.aftersaleList.refundProve.split(',')[2]
          }
          this.priceIds = this.aftersaleList.orderProductId
        }
      })
    },
    // 获取所有售后商品
    getProduct () {
      return new Promise(resolve => {
        this.$http.post(this.$api + '/pc/orderSaleafter/getSaleafteProducts', {
          orderId: this.orderId,
          page: 1,
          pageSize: 10000
        }).then(res => {
          if (res.responseCode === '0000') {
            this.saleafteProducts = res.data.list
            // 设置默认未选择属性
            this.saleafteProducts.forEach(item => {
              this.$set(item, 'checked', this.selectAll)
            })
          }
        })
        return resolve()
      })
    },
    // 全选
    checkAll (val) {
      this.checkAllId = []
      this.saleafteProducts.forEach(item => {
        item.checked = val
      })
      if (val) {
        this.saleafteProducts.forEach(item => {
          this.checkAllId.push({'productId': item.productId, 'productCover': item.productCover, 'name': item.name, 'attributeName': item.attributeName, 'orderProductId': item.orderProductId})
        })
      } else {
        this.checkAllId = []
      }
    },
    // 单选
    checkOneBox (item) {
      // 判断是否全选
      if (this.saleafteProducts.every(item => item.checked === true)) {
        this.selectAll = true
      } else {
        this.selectAll = false
      }
      // 如果被点击则存其id
      if (item.checked) {
        this.checkAllId.push({'productId': item.productId, 'productCover': item.productCover, 'name': item.name, 'attributeName': item.attributeName, 'orderProductId': item.orderProductId})
      } else {
        // 删除数组里取消选择的id
        for (let i = 0; i < this.checkAllId.length; i++) {
          if (this.checkAllId[i].productId === item.productId) {
            this.checkAllId.splice(i, 1)
          }
        }
      }
    },
    // 取消
    cancel () {
      this.checkAllId = []
      this.saleafteProducts.forEach(item => {
        this.$set(item, 'checked', this.selectAll)
      })
      this.productPop = false
    },
    // 添加
    add () {
      this.checkAllId = []
      this.imgList = []
      this.saleafteProducts.forEach(item => {
        this.$set(item, 'checked', this.selectAll)
      })
      this.productPop = true
    },
    // 提交商品
    submit () {
      this.priceIds = []
      if (this.checkAllId.length) {
        // 商品只有一件和商品多个显示的商品不同
        if (this.checkAllId.length === 1) {
          this.aftersaleList = this.checkAllId[0]
          this.priceIds = this.checkAllId[0].orderProductId
        } else {
          this.checkAllId.forEach(item => {
            this.imgList.push(item.productCover)
            this.priceIds.push(item.orderProductId)
          })
        }
        this.getSaleafterPrices() // 获取所选商品的退款金额
        this.checkAllId = []
        this.productPop = false
      } else {
        this.$message.error({
          message: '请选择商品!'
        })
      }
    },
    // 检查图片大小不超过5M
    beforeUpload (file) {
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!')
      }
      return isLt2M
    },
    uploadSuccesspictureMessage01 (file, res) {
      this.saleFrom.pictureMessage01 = file.data
    },
    uploadSuccesspictureMessage02 (file, res) {
      this.saleFrom.pictureMessage02 = file.data
    },
    uploadSuccesspictureMessage03 (file, res) {
      this.saleFrom.pictureMessage03 = file.data
    },
    // 提交表单
    subFrom (formName) {
      if (!this.isLoading) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.saleFrom.pictureMessage01) {
              this.saleFrom.pictureList.push(this.saleFrom.pictureMessage01)
            }
            if (this.saleFrom.pictureMessage02) {
              this.saleFrom.pictureList.push(this.saleFrom.pictureMessage02)
            }
            if (this.saleFrom.pictureMessage03) {
              this.saleFrom.pictureList.push(this.saleFrom.pictureMessage03)
            }
            this.isLoading = true
            this.$http.post(this.$api + '/pc/orderSaleafter/updateApply', {
              saleafterId: this.$route.query.saleafterId,
              saleafterType: this.saleFrom.saleafterType,
              goodStatus: this.saleFrom.goodStatus,
              saleafterCause: this.saleFrom.saleafterCause,
              refundPrice: this.price,
              refundExplain: this.saleFrom.refundExplain,
              refundProve: this.saleFrom.pictureList.toString()
            }).then(res => {
              if (res.responseCode === '0000') {
                this.$message.success({
                  duration: this.$store.state.duration,
                  message: res.responseMsg,
                  onClose: () => {
                    this.$router.push('/user/aftersales')
                  }
                })
              }
              setTimeout(() => {
                this.isLoading = false
              }, 3000)
            })
          } else {
            this.$message({
              message: '请填写完整信息！',
              type: 'error'
            })
            return false
          }
        })
      }
    },
    // 售后金额
    getSaleafterPrices () {
      this.$http.post(this.$api + '/pc/orderSaleafter/getSaleafterPrices', {
        ids: this.priceIds.toString()
      }).then(res => {
        if (res.responseCode === '0000') {
          this.price = res.data.prices
        }
      })
    },
    delImg (val1, val2) {
      this[val1][val2] = ''
    }
  },
  watch: {
    'saleFrom.saleafterType': function (val) {
      if (val === 2) {
        this.price = 0
      } else {
        this.getSaleafterPrices()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/scss/basic.scss';
  .main{
    width: 100%;
    .main-warpper{
      width: 1200px;
      margin: 20px auto;
      .bread-crumb{
        margin-bottom: 20px;
      }
      .title{
        color: $f_bray;
        margin-bottom: 25px;
      }
      .main-content-first{
        border: 1px solid $border_color;
        background: #fff;
        font-size: $fz_14;
        margin-bottom: 30px;
        font-size: $fz_14;
        position: relative;
        .prodcut-content{
          margin: 25px;
          padding: 25px;
          background: #f7f9ff;
          border: 1px dashed $border_color;
          display: flex;
          position: relative;
          overflow-x: auto;
          .product-img{
            width: 140px;
            height: 140px;
            border: 1px solid $border_color;
            margin-right: 25px;
          }
          .name{
            margin: 10px 0 20px;
            height: 40px;
          }
          .add{
            .el-button{
              width: 60px;
              height: 24px;
              font-size: $fz_14;
              line-height: 2px;
              padding-left: 11px;
            }
            position: absolute;
            right: 14px;
            top: 80px;
          }
        }
        .product-more{
          margin: 12px 15px 14px 15px;
          background: #f7f9ff;
          border: 1px dashed $border_color;
          height: 120px;
          position: relative;
          display: flex;
          .product-img{
            border: 1px solid $border_color;
            margin: 10px 0 10px 10px;
            height: 99px;
            width: 99px;
          }
          .add{
            .el-button{
              width: 60px;
              height: 24px;
              font-size: $fz_14;
              line-height: 2px;
              padding-left: 11px;
            }
            position: absolute;
            right: 14px;
            top: 50px;
          }
        }
        .product-pop{
          height: 826px;
          width: 610px;
          border: 1px solid $border_color;
          position: absolute;
          margin-bottom: 20px;
          right: 0;
          top: 0;
          background: #fff;
          box-shadow: 0 -1px 10px rgba(128, 128, 128, 0.3);
          .pop-dialog{
            width: 100%;
            height: 100%;
            position: relative;
            .title{
              position: absolute;
              top: 0;
              left: 0;
              height: 42px;
              width: 100%;
              line-height: 42px;
              padding-left: 15px;
              font-weight: bold;
              border-bottom: 1px solid $border_color;
              z-index: 9;
            }
            .footer{
              height: 57px;
              width: 100%;
              border-top: 1px solid $border_color;
              position: absolute;
              bottom: 0;
              left: 0;
              z-index: 9;
              padding: 0 25px;
              display: flex;
              align-items: center;
              justify-content: space-between;
              .el-button{
                width: 64px;
                height: 24px;
                line-height: 0;
              }
            }
            .product-list{
              position: absolute;
              width: 100%;
              top: 42px;
              bottom: 58px;
              padding: 20px;
              overflow: auto;
              .pro-detail{
                border: 1px solid $border_color;
                height: 118px;
                margin-bottom: 10px;
                background: $bg_title;
                display: flex;
                align-items: center;
                .check-box{
                  margin: 0 10px;
                }
                .check-img{
                  width: 98px;
                  height: 98px;
                  border: 1px solid $border_color;
                  margin-right: 15px;
                }
                .check-pro{
                  width: 330px;
                  margin-top: -10px;
                  p:first-child{
                    height: 35px;
                    margin-bottom: 15px;
                  }
                  p:nth-child(2){
                    span{float: right;}
                  }
                }
              }
            }
          }
        }
      }
      .main-content-second{
        border: 1px solid $border_color;
        background: #fff;
        font-size: $fz_14;
        padding: 30px 25px;
        .db{
          width: 250px;
        }
        .money{
          color: $red;
          font-size: $fz_16;
        }
        .into{
          color: $f_normal;
        }
        .textarea{
          width: 342px;
          height: 110px;
        }
        .uploader-bar{
          border: 0;
          padding: 0;
        }
      }
    }
  }
  .info-sub{
    text-align: center;
    margin: 40px 0;
  }
</style>
